<template>
  <div class="account-settings">
    <div class="settings-content">
        <!-- 个人信息 -->
        <n-card title="个人信息" :bordered="false" class="settings-card">
          <n-form
            ref="profileFormRef"
            :model="profileForm"
            :rules="profileRules"
            label-placement="left"
            label-width="100px"
            size="medium"
          >
            <n-form-item label="头像" path="avatar">
              <div class="avatar-upload">
                <UserAvatar
                  :user="profileForm"
                  :size="80"
                  clickable
                  @click="handleAvatarUpload"
                />
                <div class="avatar-actions">
                  <n-button size="small" @click="handleAvatarUpload">
                    更换头像
                  </n-button>
                </div>
              </div>
            </n-form-item>

            <n-form-item label="用户名" path="username">
              <n-input
                v-model:value="profileForm.username"
                placeholder="请输入用户名"
                :disabled="profileLoading"
              />
            </n-form-item>

            <n-form-item label="昵称" path="nickname">
              <n-input
                v-model:value="profileForm.nickname"
                placeholder="请输入昵称"
                :disabled="profileLoading"
              />
            </n-form-item>

            <n-form-item label="性别" path="gender">
              <n-radio-group v-model:value="profileForm.gender" :disabled="profileLoading">
                <n-radio :value="0">保密</n-radio>
                <n-radio :value="1">男</n-radio>
                <n-radio :value="2">女</n-radio>
              </n-radio-group>
            </n-form-item>

            <n-form-item label="生日" path="birthday">
              <n-date-picker
                v-model:value="birthdayTimestamp"
                type="date"
                placeholder="请选择生日"
                :disabled="profileLoading"
                style="width: 100%"
              />
            </n-form-item>

            <n-form-item label="个人签名" path="motto">
              <n-input
                v-model:value="profileForm.motto"
                type="textarea"
                placeholder="请输入个人签名"
                :disabled="profileLoading"
                :maxlength="100"
                show-count
              />
            </n-form-item>

            <n-form-item>
              <n-button
                type="primary"
                :loading="profileLoading"
                @click="handleUpdateProfile"
              >
                保存修改
              </n-button>
            </n-form-item>
          </n-form>
        </n-card>

        <!-- 账户安全 -->
        <n-card title="账户安全" :bordered="false" class="settings-card">
          <div class="security-items">
            <!-- 修改密码 -->
            <div class="security-item">
              <div class="security-info">
                <h3>登录密码</h3>
                <p>定期更换密码可以提高账户安全性</p>
              </div>
              <n-button @click="showChangePassword = true">
                修改密码
              </n-button>
            </div>

            <!-- 绑定邮箱 -->
            <div class="security-item">
              <div class="security-info">
                <h3>绑定邮箱</h3>
                <p>{{ userStore.email || '未绑定邮箱' }}</p>
              </div>
              <n-button @click="showBindEmail = true">
                {{ userStore.email ? '修改邮箱' : '绑定邮箱' }}
              </n-button>
            </div>


          </div>
        </n-card>
    </div>

    <!-- 修改密码模态框 -->
    <n-modal
      v-model:show="showChangePassword"
      preset="card"
      title="修改密码"
      style="width: 400px; max-width: 90vw;"
    >
      <ChangePasswordForm
        @success="handleChangePasswordSuccess"
        @cancel="showChangePassword = false"
      />
    </n-modal>

    <!-- 绑定邮箱模态框 -->
    <n-modal
      v-model:show="showBindEmail"
      preset="card"
      title="绑定邮箱"
      style="width: 400px; max-width: 90vw;"
    >
      <BindEmailForm
        @success="handleBindEmailSuccess"
        @cancel="showBindEmail = false"
      />
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import { useUserStore } from '@/stores/user'
import { updateUserProfile, getUserProfile } from '@/api/account'
import { commonRules } from '@/utils/validation'
import UserAvatar from '@/components/user/UserAvatar.vue'
import ChangePasswordForm from '@/components/user/ChangePasswordForm.vue'
import BindEmailForm from '@/components/user/BindEmailForm.vue'
import type { FormInst } from 'naive-ui'
import type { UpdateProfileParams } from '@/types/user'

const message = useMessage()
const userStore = useUserStore()

// 表单引用
const profileFormRef = ref<FormInst | null>(null)

// 表单数据
const profileForm = reactive<UpdateProfileParams>({
  username: '',
  nickname: '',
  gender: 0,
  birthday: '',
  motto: ''
})

// 状态
const profileLoading = ref(false)
const showChangePassword = ref(false)
const showBindEmail = ref(false)

// 生日时间戳
const birthdayTimestamp = computed({
  get: () => {
    return profileForm.birthday ? new Date(profileForm.birthday).getTime() : null
  },
  set: (value: number | null) => {
    profileForm.birthday = value ? new Date(value).toISOString().split('T')[0] : ''
  }
})

// 表单验证规则
const profileRules = {
  username: commonRules.username,
  nickname: commonRules.nickname,
  motto: commonRules.motto
}

// 初始化表单数据
const initFormData = () => {
  const user = userStore.userInfo
  if (user) {
    profileForm.username = user.username || ''
    profileForm.nickname = user.nickname || ''
    profileForm.gender = user.gender || 0
    profileForm.birthday = user.birthday || ''
    profileForm.motto = user.motto || ''
  }
}

// 处理头像上传
const handleAvatarUpload = () => {
  // 这里可以实现头像上传功能
  message.info('头像上传功能待实现')
}

// 更新个人资料
const handleUpdateProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    await profileFormRef.value.validate()
    profileLoading.value = true
    
    await updateUserProfile(profileForm)
    
    // 更新本地用户信息
    userStore.updateUserInfo(profileForm)
    
    message.success('个人资料更新成功')
  } catch (error: any) {
    console.error('更新个人资料失败:', error)
    message.error(error.message || '更新失败，请重试')
  } finally {
    profileLoading.value = false
  }
}

// 处理修改密码成功
const handleChangePasswordSuccess = () => {
  showChangePassword.value = false
  message.success('密码修改成功')
}

// 处理绑定邮箱成功
const handleBindEmailSuccess = () => {
  showBindEmail.value = false
  message.success('邮箱绑定成功')
  // 重新获取用户信息
  userStore.fetchUserInfo()
}



// 组件挂载
onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.account-settings {
  padding: 0;
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.settings-card {
  border-radius: 12px;
}

/* 头像上传 */
.avatar-upload {
  display: flex;
  align-items: center;
  gap: 16px;
}

.avatar-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 安全设置 */
.security-items {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid var(--n-border-color);
}

.security-item:last-child {
  border-bottom: none;
}

.security-info h3 {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 500;
}

.security-info p {
  margin: 0;
  font-size: 14px;
  color: var(--n-text-color-2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .account-settings {
    padding: 16px;
  }
  
  .settings-header {
    margin-bottom: 24px;
  }
  
  .settings-header h1 {
    font-size: 24px;
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .security-item button {
    width: 100%;
  }
}
</style>
